package com.umpay.privi.util;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Iterator;
import java.util.Map;

public class StringUtil {
	
	public static final String STR_FRONT = "front"; //字符串前面
	public static final String STR_BACK = "back"; //字符串后面

	/**
	 * 获取字符串字节长度
	 * @param str 
	 * @return
	 */
	public static int getLength(String str){
		if(null==str)return 0;
		try {
			return str.getBytes("GBK").length;
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException("不支持GBK编码");
		}
	}
	
	/**
	 * 
	 * description: 去除字符串前后的空格，若<code>str</code>为<code>null</code>,返回空串
	 * @param str
	 * @return
	 */ 
    public static String trim(String str) {
        return str == null ? "" : str.trim();
    }
    /**
     * 
     * description:去除字符串对象空格
     * @param str
     * @return
     */ 
    public static String trim(Object obj) {
    	return obj == null ? "" : trim(obj.toString());
    }
    /**
     * 
     * description: 判断<code>str</code>是否为空串或<code>null</code>
     * @param str
     * @return 若为空串或<code>null</code>返回<code>true</code>,否则返回<code>false</code>
     */
    public static boolean isEmpty(String str){
    	str = trim(str);
    	if("".equals(str))
    		return true;
    	else
    		return false;
    }
    /**
     * 
     * description: 判断<code>str</code>是否为空串或<code>null</code>
     * @param str
     * @return 若为空串或<code>null</code>返回<code>false</code>,否则返回<code>true</code>
     */
    public static boolean isNotEmpty(String str){
    	return !isEmpty(str);
    }
    /**
     * 
     * description: 去掉obj中string类型字段值的空格，若obj为String,则将obj去空格后返回
     * @param obj
     * @return
     */
    @SuppressWarnings("unchecked")
	public static Object trimObjectFields(Object obj){
    	if(obj == null )
    		return "";
    	Class cls = obj.getClass();
    	if(obj instanceof String)
    		return trim(obj.toString());
    	Field[] fields = cls.getDeclaredFields();
    	try{
	    	for(Field field : fields){
	    		field.setAccessible(true);
	    		if (!Modifier.isStatic(field.getModifiers()) && Modifier.isPrivate(field.getModifiers())) {
	    			Object value = field.get(obj);
	    			if(value instanceof String && null != value){
		    			String resultStr = StringUtil.trim((String)value);
		    			String name = field.getName();
		    			String setMethodName = "set"+name.substring(0, 1).toUpperCase()+name.substring(1);
		    			Method setMethod = obj.getClass().getMethod(setMethodName, String.class);
		    		    setMethod.setAccessible(true);
		    			setMethod.invoke(obj, resultStr);
		    		}
				}
	    		
	    	}
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    	return obj;
    }
    /**
     * 
     * description: 去掉obj中string类型字段值的空格，若obj为String,则将obj去空格后返回
     * @param obj
     * @return
     */
    @SuppressWarnings("unchecked")
	public static Object trimObjectFieldsOptional(Object obj){
    	if(obj == null )
    		return "";
    	Class cls = obj.getClass();
    	if(obj instanceof String)
    		return trim(obj.toString());
    	Field[] fields = cls.getDeclaredFields();
    	try{
	    	for(Field field : fields){
	    		String type = field.getType().getSimpleName().toString();
	    		String name = field.getName();
	    		if("String".equals(type)){
	    			try {
	    				String getMethod = "get"+name.substring(0, 1).toUpperCase()+name.substring(1);
	    				Method get = cls.getMethod(getMethod);
	    				String value = "";
	    				Object objvalue = get.invoke(obj);
	    				if(null!=objvalue){
	    					value = trim(objvalue.toString());
	    				}
	    				String setMethod = "set"+name.substring(0, 1).toUpperCase()+name.substring(1);
	    				Method set = cls.getMethod(setMethod,String.class);
	    				set.invoke(obj, value);
	    			} catch (Exception e) {
	    				
	    			}
	    		}
	    	}
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    	return obj;
    }
    /**
     * 去掉map中string类型字段值的空格，若value为String,则将obj去空格后返回
     * @param obj
     * @return
     */
	@SuppressWarnings("unchecked")
	public static Map trimMap(Map map){
    	if(map == null )
    		return null;
    	try{
    		Iterator it = map.entrySet().iterator();
			while (it.hasNext()) {
				Map.Entry entry = (Map.Entry) it.next();
				Object key = entry.getKey();
				Object value = entry.getValue();
				if (value instanceof String) {
					String valueStr = StringUtil.trim((String)value);
					map.put(key, valueStr);
				} else {
					if (value instanceof Map) {
						value = trimMap((Map)value);
					} else {
						value = StringUtil.trimObjectFields(value);
						map.put(key, value);
					}
				}
			} 
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    	return map;
    }
	/**
	 * 在原串的前面或者后面添加字符
	 * @param str 原字符串
	 * @param len 生产的字符串长度
	 * @param fillChar 填充的字符
	 * @param position 填充的位置，默认为原串的前面
	 * @return
	 * @see:
	 */
	public static String replenish(String str, int len, char fillChar, String position){
		str = trim(str);
		if (str.length() >= len) {
			return str;
		}
		
		String addStr = "";
		for (int i = str.length(); i < len; i++) {
			addStr += fillChar;
		}
		
		if (position.equals(STR_FRONT)) {
			str = addStr + str;
		} else {
			str = str + addStr;
		}
		
		return str;
		
	}
	public static String subString(String str,int maxLength){
		return str.substring(0,maxLength);
	}
	 /**
     * 判断字符串长度是否大于某个值
     */
    public static boolean isOverMaxLength(String str,int maxLength){
    	if(str.getBytes().length>maxLength){
    		return true;
    	}
    	return false;
    }
    
    /**
     * 根据路径获取文件名
     * @param path
     * @return
     */
    public static String getFileName(String path){
    	path = trim(path);
		if("".equals(path)){
			return path;
		}
		String srcFileName="";
		int post1 = path.lastIndexOf("/");
		int post2 = path.lastIndexOf("\\");
		if(post1<post2){
			srcFileName = path.substring(post2+1);
		}else{
			srcFileName = path.substring(post1+1);
		}
		return srcFileName;
    }
    
	/**
	 * 使用java正则表达式去掉多余的.与0
	 * @param s
	 * @return 
	 */
	public static String subZeroAndDot(String s){
		if(s.indexOf(".") > 0){
			s = s.replaceAll("[0]*$", "");//去掉多余的0
			if (String.valueOf(s.charAt(s.length() - 1)).equals(".")) {
				s = s.substring(0, s.length() - 1);
			}
			//s = s.replaceAll("[.]$", "");//如最后一位是.则去掉
		}
		return s;
	}
	/**
	 * desc:过滤特殊字符，例如%，<
	 * <p>创建人：chengliuyun , Feb 21, 2013 4:30:42 PM</p>
	 * @param input
	 * @return
	 */
	public static String filterString(String input) {
		if (input == null || "".equals(input.trim()) || "null".equals(input.trim())) {
			return "";
		}
		// 去掉所有html元素, sql 元素
		String ret = input.replaceAll("\\&[a-zA-Z]{1,10};", "").replaceAll("<[^>]*>",
				"").replaceAll("[(/>)<]", "").replace("%", "").
				replaceAll(" and ", "").replaceAll(" AND ", "").replaceAll(" or ", "").replaceAll(" OR ", "");
		return ret;
	}
	@SuppressWarnings("unchecked")
	public static void main(String[] args) {
//		Map reqMap = new HashMap();
//		reqMap.put(XmlData.ACCOUNTID, "02000000040507            ");
//		reqMap.put(XmlData.USERID, 123);
//		Map mediaItems = new HashMap();
//		mediaItems.put(XmlData.ACCOUNTID, "1     ");
//		mediaItems.put(XmlData.NAME, "hello1");
//		reqMap.put("mediaItems", mediaItems);
//		System.out.println(reqMap);
//		
//		reqMap = StringUtil.trimMap(reqMap);
//		System.out.println(reqMap);
		//0001259968
		String str = "1259968";
		int len = 10; 
		char fillChar = '0';
		String position = STR_FRONT;
		String resultStr = replenish(str, len, fillChar, position);
		System.out.println(resultStr);
		
	}
    
}
